package com.macro.mall.portal.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.util.TencentMapUtils;
import com.macro.mall.mapper.BmsConfigMapper;
import com.macro.mall.mapper.BmsDailyAttendanceRecordMapper;
import com.macro.mall.model.BmsDailyAttendanceRecord;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.service.BmsDailyAttendanceRecordService;
import com.macro.mall.portal.util.MemberUtils;
import com.macro.mall.query.BmsDailyAttendanceRecordQuery;
import com.macro.mall.request.BmsDailyAttendanceRecordParam;

import cn.hutool.core.date.LocalDateTimeUtil;
import net.logstash.logback.util.StringUtils;

@Service
public class BmsDailyAttendanceRecordServiceImpl implements BmsDailyAttendanceRecordService {

    @Autowired
    private BmsConfigMapper configMapper;

    @Autowired
    private BmsDailyAttendanceRecordMapper baseMapper;

    @Override
    public List<BmsDailyAttendanceRecord> findList(BmsDailyAttendanceRecordQuery query) {
        Integer pageNum = query.getPageNum();
        Integer pageSize = query.getPageSize();
        if (Objects.nonNull(pageNum) && Objects.nonNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<BmsDailyAttendanceRecord> list = baseMapper.findList(query);
        return list;
    }

    @Override
    public int create(BmsDailyAttendanceRecordParam BmsDailyAttendanceRecordParam) {
        BmsDailyAttendanceRecord BmsDailyAttendanceRecord = new BmsDailyAttendanceRecord();
        BeanUtils.copyProperties(BmsDailyAttendanceRecordParam, BmsDailyAttendanceRecord);
        MemberUtils.setCreation(BmsDailyAttendanceRecord);
        return baseMapper.insert(BmsDailyAttendanceRecord);
    }

    @Override
    public int update(BmsDailyAttendanceRecordParam param) {
        BmsDailyAttendanceRecord entity = baseMapper.getById(param.getId());
        BeanUtils.copyProperties(param, entity);
        MemberUtils.setEdition(entity);
        return baseMapper.updateById(entity);
    }

    @Override
    public BmsDailyAttendanceRecord getById(Long id) {
        return baseMapper.getById(id);
    }

    @Override
    public int delete(List<Long> ids) {
        return baseMapper.updateDeleteId(ids);
    }

    @Override
    public int clockIn(BmsDailyAttendanceRecordParam param) {
        BmsDailyAttendanceRecord entity = this.getTodayDetail();
        param.setId(entity.getId());
        MemberUtils.setEdition(entity);
        if (entity.getClockInTime() == null) { // 上班
            entity.setClockInTime(LocalDateTimeUtil.now());
            entity.setClockInAddress(param.getAddress());
            entity.setClockInLatitude(param.getLatitude());
            entity.setClockInLongitude(param.getLongitude());
        } else { // 下班
            entity.setClockOutTime(LocalDateTimeUtil.now());
            entity.setClockOutAddress(param.getAddress());
            entity.setClockOutLatitude(param.getLatitude());
            entity.setClockOutLongitude(param.getLongitude());
        }
        return baseMapper.updateById(entity);
    }

    @Override
    public BmsDailyAttendanceRecord getTodayDetail() {
        UmsMember user = MemberUtils.getUser();
        BmsDailyAttendanceRecord entity = baseMapper.getTodayDetail(user.getId());
        if (entity == null) {
            throw new RuntimeException("不是内部人员或考勤记录未生成");
        }
        return entity;
    }

    /**
     * @Title isCanClockIn
     * @Description 是否可打卡
     * @param lng 经度
     * @param lat 纬度
     * @return boolean
     * @author zhaojianlin
     * @date 创建时间：2024年8月22日 下午5:16:03
     * @version V1.0.0
     * @Copyright 2024 赵健林
     * @throws
     */
    @Override
    public boolean isCanClockIn(BmsDailyAttendanceRecordQuery query) {
        boolean flag = false;
        if (query == null || StringUtils.isBlank(query.getLat())
                || StringUtils.isBlank(query.getLng())) {
            throw new RuntimeException("获取当前所在位置失败，请刷新后重试！");
        }
        // 获取考勤范围
        String attendanceConfig = configMapper.getValueByCode("ATTENDANCE_CONFIG");
        if (StringUtils.isBlank(attendanceConfig)) {
            throw new RuntimeException("考勤参数未设置，请联系管理员进行设置！");
        }
        JSONObject entity = JSON.parseObject(attendanceConfig);
        String from = entity.getString("lat") + "," + entity.getString("lng");
        String to = query.getLat() + "," + query.getLng();
        BigDecimal range = entity.getBigDecimal("range");

        // 获取考勤范围
        String key = configMapper.getValueByCode("TENCENT_KEY");
        if (StringUtils.isBlank(key)) {
            throw new RuntimeException("腾讯地图KEY未设置，请联系管理员进行设置！");
        }
        BigDecimal distance = TencentMapUtils.getSingleDistance(from, to, key);
        if (distance.compareTo(range) <= 0) {
            flag = true; 
        }
        return flag;
    }

}
